<?php
/**
 * Created by PhpStorm.
 * User: MrHung
 * Date: 1/22/14
 * Time: 5:27 PM
 */

namespace Frontend\Controller;


use Admin\Model\AdminUserTable;
use Zend\Authentication\Validator\Authentication;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\Validator\File\UploadFile;
use Zend\View\Model\ViewModel;
use Admin\Model\AdminUser;
use \Velacolib\Utility\Utility;
use Zend\Form\Form;
use Zend\Form\Element;
class LoginController extends AbstractActionController
{

       protected $translator;

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->translator = Utility::translate();
        $this->layout('frontend/layout');
        return parent::onDispatch($e);
    }
    public function indexAction(){
    }

    public function loginAction(){
        $response['redirect'] = false;
        $aut = new AuthenticationService();

        if ($aut->hasIdentity() == 1) {
            $response['result'] = false;
            $response['message'] = $this->translator->translate('You are logged in');
            $response['isLogin'] = true;
            $response['redirect'] = false;
        }

        $response['result'] = false;
		

        if ($this->getRequest()->isPost()) {
			
            $data = $this->params()->fromPost();

            $user_table = Utility::UserGateway('Admin\Model\AdminUserTable');

            $user_table->setLoginUser($data);

            $login_obj = new AuthenticationService(null, $user_table);

            $login_obj->authenticate();

            //$test = new AuthenticationService();
            //echo '<pre>';
            ///print_r($login_obj->getIdentity());die;

            if ($login_obj->hasIdentity() == 1) {			
              /* if ($login_obj->getIdentity()->confirm == 0) {
                    $response['isLogin'] = false;
                    $response['result'] = false;
                    $response['message'] = 'Bạn chưa xác nhận tài khoản qua email ....';
                    $response['email'] = $login_obj->getIdentity()->email;
                    $response['time_reg'] = $login_obj->getIdentity()->time_reg;
                    $response['name'] = $login_obj->getIdentity()->name;
                    $response['confirm'] = 0;
                } else {   */
                    $response['result'] = true;
                    $response['message'] = $this->translator->translate('Login success');
                    $response['user_info'] = Utility::getInfoUser($login_obj->getIdentity()->userid) ;
                  //  $response['redirect'] = true;
                 //   $response['url'] = '/';
              //  }
            }else {

                $response['result'] = false;

                $response['message'] = $this->translator->translate('Wrong user or password , Please try again!');

            }
            header("ContentType: application/json");

            echo json_encode($response);
            die();
        }
    }

    public function isloginAction(){
        $aut = new AuthenticationService();
        if ($aut->hasIdentity() == 1) {
            $response['result'] = true;
            $response['message'] = $this->translator->translate('You are logged in');
            $response['isLogin'] = true;

        }
        echo json_encode($response);
        die();
    }
    public function authEmailForgotAction(){
        $request = $this->getRequest();
        if($request->isPost()){
            $data = $this->params()->fromPost();
             $userModel = Utility::UserGateway("Admin\Model\AdminUserTable");
            $user =   $userModel->getUserByEmail($data['email']);
            if(is_object($user))
            {
                $userEmail = $user->email;
            } else{
                $userEmail = '';
            }
            if($data['email'] == $userEmail){
                $pass = time();
                $newpass =  md5($user->email.$pass);
                $user->password = $newpass;
                $userModel->saveUser($user);
                //sending email recover password to user
                $smtp_option = null ;
                $senderInfo = array(
                    'email' => 'admin@vela.com',
                    'name' => 'Vela Corp'

                );

                $RecipientInfo = array(
                    'email' => $user->email,
                    'name' => $user->name,
                    'password' => $pass,
                );

                $template_path = 'admin/email/tpl/forgotpass';

                $subject = 'Vela Recover password';

                Utility::SendMail(false, $smtp_option = null, $senderInfo, $RecipientInfo, $template_path, $subject);


                $response['result'] = true;
                $response['message'] = $this->translator->translate("Mật khẩu mới đã đc gửi về Email của bạn! vui lòng kiểm tra lại!");
            }else{
                $response['result'] = false;
                $response['message'] = $this->translator->translate("Email không tồn tại");
            }


        }else{
            $response['result'] = false;
            $response['message'] = $this->translator->translate('Method is not allowed');
        }

        echo json_encode($response);die;

    }
    public function fbAction(){
        $facebook = new \Facebook(array(
            'appId'=>'509304975858722',
            'secret'=>'4ac3ecd5d449f825da621626d675ff21',
            'cookie'=>true
        ));

        $user = $facebook->getUser();

        if ($user) {
            try {
                $user_profile = $facebook->api('/me');
            }
            catch (Exception $e) {
                echo $e->getMessage();
                exit();
            }
               /* user_profile is array with param
                * =>  id,name,first_name,last_name,link,hometown,location,work,favorite_teams,education,gender,email,
                * timezone,locale,languages,verified,,updated_time,username
                * hometown is array => id,name
                */
            $fb_picture = "https://graph.facebook.com/".$user_profile['id']."/picture";

            $user_save = array(
                'name' => $user_profile['first_name'].' '.$user_profile['last_name'],
                'email' => $user_profile['email'],
                'avatar' => $fb_picture,
                'time_reg'=>time(),
                'user_type'=>2,
                'confirm'=>1
            );
            /*
             * insert user into userTable
             */

            $userTalbe = new AdminUser();
            $userModel = Utility::UserGateway("Admin\Model\AdminUserTable");

            // check true /false email
            $email =  $userModel->getUserByEmail($user_save['email']);

           if(is_object($email)){
              // authenticate
               $login_user['username'] = $user_save['email'];

               $userModel->setLoginUser($login_user);

               $login_obj = new AuthenticationService(null, $userModel);

               $login_obj->authenticate();
               $response['result'] = true;
               $this->redirect()->toRoute('home');
               //echo json_encode($response);die;

           }else{
               // add user inti db
               $userTalbe->exchangeArray($user_save);

               $userModel->saveUser($userTalbe);

               // authenticate

               $login_user['username'] = $user_save['email'];

               $userModel->setLoginUser($login_user);

               $login_obj = new AuthenticationService(null, $userModel);

               $login_obj->authenticate();
               $this->redirect()->toRoute('home');
              // $response['result'] = true;
              // echo json_encode($response);die;

           }


        }else{
            exit($this->translator->translate('Login failed'));
        }


    }
} 